{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 导入OpenAI库，并创建OpenAI客户端\n",
    "from dotenv import load_dotenv\n",
    "load_dotenv()\n",
    "from openai import OpenAI\n",
    "client = OpenAI()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>日期</th>\n",
       "      <th>零基础学机器学习</th>\n",
       "      <th>数据分析咖哥十话</th>\n",
       "      <th>GPT图解</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>31/3/2022</td>\n",
       "      <td>303.032760</td>\n",
       "      <td>985.615033</td>\n",
       "      <td>909.762701</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>30/6/2022</td>\n",
       "      <td>504.892977</td>\n",
       "      <td>871.129109</td>\n",
       "      <td>1023.037873</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>30/9/2022</td>\n",
       "      <td>576.723513</td>\n",
       "      <td>1035.950790</td>\n",
       "      <td>1080.552675</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>31/12/2022</td>\n",
       "      <td>670.501822</td>\n",
       "      <td>1068.182030</td>\n",
       "      <td>1148.976637</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>31/3/2023</td>\n",
       "      <td>766.792751</td>\n",
       "      <td>718.352429</td>\n",
       "      <td>1204.730960</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "           日期    零基础学机器学习     数据分析咖哥十话        GPT图解\n",
       "0   31/3/2022  303.032760   985.615033   909.762701\n",
       "1   30/6/2022  504.892977   871.129109  1023.037873\n",
       "2   30/9/2022  576.723513  1035.950790  1080.552675\n",
       "3  31/12/2022  670.501822  1068.182030  1148.976637\n",
       "4   31/3/2023  766.792751   718.352429  1204.730960"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 导入数据文件\n",
    "import pandas as pd\n",
    "file_path = 'sales_data.csv'\n",
    "sales_data = pd.read_csv(file_path)\n",
    "sales_data.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Assistant(id='asst_Brzqgi6j8cjuvQtRqMlCZxAO', created_at=1714004967, description=None, instructions='作为一名数据科学助理，当给定数据和一个查询时，你能编写适当的代码并创建适当的可视化。', metadata={}, model='gpt-4-0125-preview', name=None, object='assistant', tools=[CodeInterpreterTool(type='code_interpreter')], tool_resources=ToolResources(code_interpreter=ToolResourcesCodeInterpreter(file_ids=['file-vREOueLEpmTVGmNjF8KMaYrq']), file_search=None), top_p=1.0, temperature=1.0, response_format='auto')\n"
     ]
    }
   ],
   "source": [
    "# 创建文件\n",
    "file = client.files.create(\n",
    "  file=open(file_path, \"rb\"),\n",
    "  purpose='assistants',\n",
    ")\n",
    "\n",
    "# 创建一个包含这个文件的助手\n",
    "assistant = client.beta.assistants.create(\n",
    "  instructions=\"作为一名数据科学助理，当给定数据和一个查询时，你能编写适当的代码并创建适当的可视化。\",\n",
    "  model=\"gpt-4-0125-preview\",\n",
    "  tools=[\n",
    "    {\"type\": \"code_interpreter\"}\n",
    "  ],\n",
    "  tool_resources={\n",
    "    \"code_interpreter\": {\n",
    "      \"file_ids\": [file.id]  # Here we add the file id\n",
    "    }\n",
    "  }\n",
    ")\n",
    "print(assistant)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Thread(id='thread_XU3pjbxtGi4h2KyNXzg5nOA4', created_at=1714004967, metadata={}, object='thread', tool_resources=ToolResources(code_interpreter=ToolResourcesCodeInterpreter(file_ids=['file-vREOueLEpmTVGmNjF8KMaYrq']), file_search=None))\n"
     ]
    }
   ],
   "source": [
    "# 创建对话线程并运行\n",
    "thread = client.beta.threads.create(\n",
    "  messages=[\n",
    "    {\n",
    "      \"role\": \"user\",\n",
    "      \"content\": \"计算从2022年到2025年每个季度的总销售额，并通过不同的产品将其可视化为折线图，产品线条颜色分别为红，蓝，绿。\",\n",
    "      \"attachments\": [\n",
    "        {\n",
    "          \"file_id\": file.id,\n",
    "          \"tools\": [\n",
    "            { \"type\": \"code_interpreter\" }\n",
    "          ]\n",
    "        }\n",
    "      ]\n",
    "    }\n",
    "  ]\n",
    ")\n",
    "print(thread)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Run(id='run_Ss6o8VT9qDYsq1vtf9CSK38L', assistant_id='asst_Brzqgi6j8cjuvQtRqMlCZxAO', cancelled_at=None, completed_at=None, created_at=1714004968, expires_at=1714005568, failed_at=None, incomplete_details=None, instructions='作为一名数据科学助理，当给定数据和一个查询时，你能编写适当的代码并创建适当的可视化。', last_error=None, max_completion_tokens=None, max_prompt_tokens=None, metadata={}, model='gpt-4-0125-preview', object='thread.run', required_action=None, response_format='auto', started_at=None, status='queued', thread_id='thread_XU3pjbxtGi4h2KyNXzg5nOA4', tool_choice='auto', tools=[CodeInterpreterTool(type='code_interpreter')], truncation_strategy=TruncationStrategy(type='auto', last_messages=None), usage=None, temperature=1.0, top_p=1.0, tool_resources={})\n"
     ]
    }
   ],
   "source": [
    "# 创建Run来运行和助手的对话\n",
    "run = client.beta.threads.runs.create(\n",
    "    thread_id=thread.id,\n",
    "    assistant_id=assistant.id,\n",
    ")\n",
    "print(run)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "您的Assistant正在努力做图表呢...\n",
      "当前Message: TextContentBlock(text=Text(annotations=[], value='计算从2022年到2025年每个季度的总销售额，并通过不同的产品将其可视化为折线图，产品线条颜色分别为红，蓝，绿。'), type='text')\n",
      "您的Assistant正在努力做图表呢...\n",
      "您的Assistant正在努力做图表呢...\n",
      "当前Message: TextContentBlock(text=Text(annotations=[], value='数据确实包含从2022年3月31日到2025年12月31日的日期范围，符合要求。接下来，我们将计算每个季度的总销售额，并通过折线图进行可视化，使用指定的颜色表示不同的产品。'), type='text')\n",
      "您的Assistant正在努力做图表呢...\n",
      "当前Message: TextContentBlock(text=Text(annotations=[], value='数据确实包含从2022年3月31日到2025年12月31日的日期范围，符合要求。接下来，我们将计算每个季度的总销售额，并通过折线图进行可视化，使用指定的颜色表示不同的产品。'), type='text')\n",
      "您的Assistant正在努力做图表呢...\n",
      "图表已创建！\n",
      "当前Message: ImageFileContentBlock(image_file=ImageFile(file_id='file-yMlgsnfVuwi2k5ybnvHfjpcV'), type='image_file')\n"
     ]
    }
   ],
   "source": [
    "# 检查并等待可视化完成\n",
    "import time\n",
    "while True:\n",
    "    messages = client.beta.threads.messages.list(thread_id=thread.id)\n",
    "    try:\n",
    "        # 检查是否创建了图像\n",
    "        messages.data[0].content[0].image_file\n",
    "        # 等待运行完成\n",
    "        time.sleep(5)\n",
    "        print('图表已创建！')\n",
    "        if messages.data and messages.data[0].content:\n",
    "            print('当前Message:', messages.data[0].content[0])\n",
    "        break\n",
    "    except:\n",
    "        time.sleep(10)\n",
    "        print('您的Assistant正在努力做图表呢...')\n",
    "        if messages.data and messages.data[0].content:\n",
    "            print('当前Message:', messages.data[0].content[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 转换输出文件为PNG格式\n",
    "def convert_file_to_png(file_id, write_path):\n",
    "    data = client.files.content(file_id)\n",
    "    data_bytes = data.read()\n",
    "    with open(write_path, \"wb\") as file:\n",
    "        file.write(data_bytes)\n",
    "\n",
    "plot_file_id = messages.data[0].content[0].image_file.file_id\n",
    "image_path = \"咖哥图书销量.png\"\n",
    "convert_file_to_png(plot_file_id,image_path)\n",
    "\n",
    "# 上传图表\n",
    "plot_file = client.files.create(\n",
    "  file=open(image_path, \"rb\"),\n",
    "  purpose='assistants'\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[ImageFileContentBlock(image_file=ImageFile(file_id='file-yMlgsnfVuwi2k5ybnvHfjpcV'), type='image_file'),\n",
       " TextContentBlock(text=Text(annotations=[], value='数据确实包含从2022年3月31日到2025年12月31日的日期范围，符合要求。接下来，我们将计算每个季度的总销售额，并通过折线图进行可视化，使用指定的颜色表示不同的产品。'), type='text'),\n",
       " TextContentBlock(text=Text(annotations=[], value='文件包含了从2022年到2025年每个季度的销售数据，列名为“日期”，“零基础学机器学习”，“数据分析咖哥十话”，以及“GPT图解”。接下来，我们将：\\n\\n1. 检查日期范围以确保数据覆盖从2022年到2025年。\\n2. 计算每个季度的总销售额。\\n3. 通过不同产品将总销售额可视化为折线图，产品线条颜色分别为红，蓝，绿。\\n\\n让我们从检查日期范围开始。'), type='text'),\n",
       " TextContentBlock(text=Text(annotations=[], value='首先，我将检查上传的文件内容，以了解数据的格式和结构。安装好文件之后，我们可以继续计算总销售额，并按要求进行可视化。'), type='text'),\n",
       " TextContentBlock(text=Text(annotations=[], value='计算从2022年到2025年每个季度的总销售额，并通过不同的产品将其可视化为折线图，产品线条颜色分别为红，蓝，绿。'), type='text')]"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 看看助手整个的思维和行动过程\n",
    "messages = client.beta.threads.messages.list(thread_id=thread.id)\n",
    "[message.content[0] for message in messages.data]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义提交用户的消息的函数\n",
    "def submit_message_wait_completion(assistant_id, thread, user_message, file_ids=None):\n",
    "    # 检查并等待活跃的Run完成\n",
    "    for run in client.beta.threads.runs.list(thread_id=thread.id).data:\n",
    "        if run.status == 'in_progress':\n",
    "            print(f\"等待Run {run.id} 完成...\")\n",
    "            while True:\n",
    "                run_status = client.beta.threads.runs.retrieve(thread_id=thread.id, run_id=run.id).status\n",
    "                if run_status in ['succeeded', 'failed']:\n",
    "                    break\n",
    "                time.sleep(5)  # 等待5秒后再次检查状态\n",
    "\n",
    "    # 提交消息\n",
    "    params = {\n",
    "        'thread_id': thread.id,\n",
    "        'role': 'user',\n",
    "        'content': user_message,\n",
    "    }\n",
    "    # 设置attachments\n",
    "    if file_ids:        \n",
    "        attachments = [{\"file_id\": file_id, \"tools\": [ {\"type\": \"code_interpreter\"}]} for file_id in file_ids]\n",
    "        params['attachments'] = attachments\n",
    "    client.beta.threads.messages.create(**params)\n",
    "\n",
    "    # 创建Run\n",
    "    run = client.beta.threads.runs.create(thread_id=thread.id, assistant_id=assistant_id)\n",
    "    return run \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Run(id='run_tYw85XwXuoQIbvq9zmSuWYmT', assistant_id='asst_Brzqgi6j8cjuvQtRqMlCZxAO', cancelled_at=None, completed_at=None, created_at=1714005029, expires_at=1714005629, failed_at=None, incomplete_details=None, instructions='作为一名数据科学助理，当给定数据和一个查询时，你能编写适当的代码并创建适当的可视化。', last_error=None, max_completion_tokens=None, max_prompt_tokens=None, metadata={}, model='gpt-4-0125-preview', object='thread.run', required_action=None, response_format='auto', started_at=None, status='queued', thread_id='thread_XU3pjbxtGi4h2KyNXzg5nOA4', tool_choice='auto', tools=[CodeInterpreterTool(type='code_interpreter')], truncation_strategy=TruncationStrategy(type='auto', last_messages=None), usage=None, temperature=1.0, top_p=1.0, tool_resources={})"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 使用submit_message函数, 来发送请求，让助手生成洞察\n",
    "submit_message_wait_completion(assistant.id, thread, \"请根据你刚才创建的图表，给我两个约20字的句子，描述最重要的洞察。这将用于幻灯片展示，揭示出数据背后的'秘密'。\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1. \"GPT图解\"的销售额稳步上升，显示出强劲的市场需求和增长潜力。\n",
      "2. \"数据分析咖哥十话\"虽有起伏，但整体上呈现出稳定增长的趋势。\n"
     ]
    }
   ],
   "source": [
    "# 获取对话线程的响应\n",
    "def get_response(thread):\n",
    "    return client.beta.threads.messages.list(thread_id=thread.id)\n",
    "\n",
    "# 等待响应并打印洞察\n",
    "time.sleep(10) # 假设助理需要一些时间来生成洞察\n",
    "response = get_response(thread)\n",
    "bullet_points = response.data[0].content[0].text.value\n",
    "print(bullet_points)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Run(id='run_LBxNrn3TiRFJGsQJYeUSSwCy', assistant_id='asst_Brzqgi6j8cjuvQtRqMlCZxAO', cancelled_at=None, completed_at=None, created_at=1714005040, expires_at=1714005640, failed_at=None, incomplete_details=None, instructions='作为一名数据科学助理，当给定数据和一个查询时，你能编写适当的代码并创建适当的可视化。', last_error=None, max_completion_tokens=None, max_prompt_tokens=None, metadata={}, model='gpt-4-0125-preview', object='thread.run', required_action=None, response_format='auto', started_at=None, status='queued', thread_id='thread_XU3pjbxtGi4h2KyNXzg5nOA4', tool_choice='auto', tools=[CodeInterpreterTool(type='code_interpreter')], truncation_strategy=TruncationStrategy(type='auto', last_messages=None), usage=None, temperature=1.0, top_p=1.0, tool_resources={})"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 根据见解生成标题 \n",
    "submit_message_wait_completion(assistant.id, thread, \"根据你创建的情节和要点，为幻灯片想一个非常简短的标题。它应该只反映你得出的主要见解。\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\"强劲增长：GPT图解与数据分析的市场突破\"\n"
     ]
    }
   ],
   "source": [
    "# 等待响应并打印标题\n",
    "time.sleep(10) # 等待助理生成标题\n",
    "response = get_response(thread)\n",
    "title = response.data[0].content[0].text.value\n",
    "print(title)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 提供花语秘境公司的说明\n",
    "company_summary = \"我们是网络鲜花批发商，但是我们董事长也写IT图书！\"\n",
    "\n",
    "# 使用DALL-E 3生成图片\n",
    "response = client.images.generate(\n",
    "  model='dall-e-3',\n",
    "  prompt=f\"根据这个公司概述 {company_summary}, \\\n",
    "           创建一张展示成长和前进道路的启发性照片。这将用于季度销售规划会议\",\n",
    "       size=\"1024x1024\",\n",
    "       quality=\"hd\",\n",
    "       n=1\n",
    ")\n",
    "image_url = response.data[0].url\n",
    "\n",
    "# 获取DALL-E 3生成的图片\n",
    "import requests\n",
    "dalle_img_path = '花语秘境咖哥.png'\n",
    "img = requests.get(image_url)\n",
    "\n",
    "# 将图片保存到本地\n",
    "with open(dalle_img_path,'wb') as file:\n",
    "  file.write(img.content)\n",
    "\n",
    "# 上传图片提供给助手做为PPT素材\n",
    "dalle_file = client.files.create(\n",
    "  file=open(dalle_img_path, \"rb\"),\n",
    "  purpose='assistants'\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "您的Assistant正在努力制作幻灯片...\n",
      "您的Assistant正在努力制作幻灯片...\n",
      "您的Assistant正在努力制作幻灯片...\n",
      "您的Assistant正在努力制作幻灯片...\n",
      "您的Assistant正在努力制作幻灯片...\n",
      "您的Assistant正在努力制作幻灯片...\n",
      "您的Assistant正在努力制作幻灯片...\n",
      "您的Assistant正在努力制作幻灯片...\n",
      "成功检索到 pptx_id: file-sMIsjd50FCApZCS9dZbhRbsb\n"
     ]
    }
   ],
   "source": [
    "title_template = \"\"\"\n",
    "from pptx import Presentation\n",
    "from pptx.util import Inches, Pt\n",
    "from pptx.enum.text import PP_PARAGRAPH_ALIGNMENT\n",
    "from pptx.dml.color import RGBColor\n",
    "\n",
    "# 创建新的演示文稿对象\n",
    "prs = Presentation()\n",
    "\n",
    "# 添加一个空白的幻灯片布局\n",
    "blank_slide_layout = prs.slide_layouts[6]\n",
    "slide = prs.slides.add_slide(blank_slide_layout)\n",
    "\n",
    "# 将幻灯片的背景颜色设置为黑色\n",
    "background = slide.background\n",
    "fill = background.fill\n",
    "fill.solid()\n",
    "fill.fore_color.rgb = RGBColor(0, 0, 0)\n",
    "\n",
    "# 在幻灯片左侧添加图片，上下留有边距\n",
    "left = Inches(0)\n",
    "top = Inches(0)\n",
    "height = prs.slide_height\n",
    "width = prs.slide_width * 3/5\n",
    "pic = slide.shapes.add_picture(image_path, left, top, width=width, height=height)\n",
    "\n",
    "# 在较高位置添加标题文本框\n",
    "left = prs.slide_width * 3/5\n",
    "top = Inches(2)\n",
    "width = prs.slide_width * 2/5\n",
    "height = Inches(1)\n",
    "title_box = slide.shapes.add_textbox(left, top, width, height)\n",
    "title_frame = title_box.text_frame\n",
    "title_p = title_frame.add_paragraph()\n",
    "title_p.text = title_text\n",
    "title_p.font.bold = True\n",
    "title_p.font.size = Pt(38)\n",
    "title_p.font.color.rgb = RGBColor(255, 255, 255)\n",
    "title_p.alignment = PP_PARAGRAPH_ALIGNMENT.CENTER\n",
    "\n",
    "# 添加副标题文本框\n",
    "left = prs.slide_width * 3/5\n",
    "top = Inches(3)\n",
    "width = prs.slide_width * 2/5\n",
    "height = Inches(1)\n",
    "subtitle_box = slide.shapes.add_textbox(left, top, width, height)\n",
    "subtitle_frame = subtitle_box.text_frame\n",
    "subtitle_p = subtitle_frame.add_paragraph()\n",
    "subtitle_p.text = subtitle_text\n",
    "subtitle_p.font.size = Pt(22)\n",
    "subtitle_p.font.color.rgb = RGBColor(255, 255, 255)\n",
    "subtitle_p.alignment = PP_PARAGRAPH_ALIGNMENT.CENTER\n",
    "\"\"\"\n",
    "\n",
    "data_vis_template = \"\"\"\n",
    "from pptx import Presentation\n",
    "from pptx.util import Inches, Pt\n",
    "from pptx.enum.text import PP_PARAGRAPH_ALIGNMENT\n",
    "from pptx.dml.color import RGBColor\n",
    "\n",
    "# 创建新的演示文稿对象\n",
    "prs = Presentation()\n",
    "\n",
    "# 添加一个空白的幻灯片布局\n",
    "blank_slide_layout = prs.slide_layouts[6]\n",
    "slide = prs.slides.add_slide(blank_slide_layout)\n",
    "\n",
    "# 将幻灯片的背景颜色设置为黑色\n",
    "background = slide.background\n",
    "fill = background.fill\n",
    "fill.solid()\n",
    "fill.fore_color.rgb = RGBColor(0, 0, 0)\n",
    "\n",
    "# 定义占位符\n",
    "image_path = data_vis_img\n",
    "title_text = \"提升利润：在线销售与直销优化的主导地位\"\n",
    "bullet_points = \"• 在线销售在各个季度中始终领先于盈利能力，表明了强大的数字市场存在。\\n• 直销表现出波动，表明该渠道的表现变化和需要针对性改进的必要性。\"\n",
    "\n",
    "# 在幻灯片左侧添加图片占位符\n",
    "left = Inches(0.2)\n",
    "top = Inches(1.8)\n",
    "height = prs.slide_height - Inches(3)\n",
    "width = prs.slide_width * 3/5\n",
    "pic = slide.shapes.add_picture(image_path, left, top, width=width, height=height)\n",
    "\n",
    "# 添加覆盖整个宽度的标题文本\n",
    "left = Inches(0)\n",
    "top = Inches(0)\n",
    "width = prs.slide_width\n",
    "height = Inches(1)\n",
    "title_box = slide.shapes.add_textbox(left, top, width, height)\n",
    "title_frame = title_box.text_frame\n",
    "title_frame.margin_top = Inches(0.1)\n",
    "title_p = title_frame.add_paragraph()\n",
    "title_p.text = title_text\n",
    "title_p.font.bold = True\n",
    "title_p.font.size = Pt(28)\n",
    "title_p.font.color.rgb = RGBColor(255, 255, 255)\n",
    "title_p.alignment = PP_PARAGRAPH_ALIGNMENT.CENTER\n",
    "\n",
    "# 添加硬编码的“关键见解”文本和项目符号列表\n",
    "left = prs.slide_width * 2/3\n",
    "top = Inches(1.5)\n",
    "width = prs.slide_width * 1/3\n",
    "height = Inches(4.5)\n",
    "insights_box = slide.shapes.add_textbox(left, top, width, height)\n",
    "insights_frame = insights_box.text_frame\n",
    "insights_p = insights_frame.add_paragraph()\n",
    "insights_p.text = \"关键见解：\"\n",
    "insights_p.font.bold = True\n",
    "insights_p.font.size = Pt(24)\n",
    "insights_p.font.color.rgb = RGBColor(0, 128, 100)\n",
    "insights_p.alignment = PP_PARAGRAPH_ALIGNMENT.LEFT\n",
    "insights_frame.add_paragraph()\n",
    "\n",
    "\n",
    "bullet_p = insights_frame.add_paragraph()\n",
    "bullet_p.text = bullet_points\n",
    "bullet_p.font.size = Pt(12)\n",
    "bullet_p.font.color.rgb = RGBColor(255, 255, 255)\n",
    "bullet_p.line_spacing = 1.5\n",
    "\"\"\"\n",
    "\n",
    "title_text = \"花语秘境\"\n",
    "subtitle_text = \"2025年销售大会\"\n",
    "\n",
    "submit_message_wait_completion(assistant.id,thread,f\"使用包含的代码模板创建符合模板格式的PPTX幻灯片，但使用本消息中包含的图片、公司名称/标题和文件名/副标题：\\\n",
    "{title_template}。重要提示：在此第一张幻灯片中使用本消息中包含的图片文件作为image_path图像，并使用公司名称 {title_text} 作为title_text变量，\\\n",
    "  使用副标题文本 {subtitle_text} 作为subtitle_text变量。\\\n",
    "    接着，使用以下代码模板创建第二张幻灯片：{data_vis_template}，创建符合模板格式的PPTX幻灯片，但使用公司名称/标题和文件名/副标题：\\\n",
    "{data_vis_template}。重要提示：使用您之前在本线程中创建的第二个附图（折线图）作为data_vis_img图像，并使用您之前创建的数据可视化标题作为title_text变量，\\\n",
    "  使用您之前创建的见解项目符号列表作为bullet_points变量。将这两张幻灯片输出为.pptx文件。确保输出为两张幻灯片，每张幻灯片都符合本消息中给出的相应模板。\",\n",
    "              file_ids=[dalle_file.id, plot_file.id]\n",
    ")\n",
    "\n",
    "\n",
    "# 等待助手完成PPT创建任务\n",
    "while True:\n",
    "    try:\n",
    "        response = get_response(thread)\n",
    "        pptx_id = response.data[0].content[0].text.annotations[0].file_path.file_id\n",
    "        print(\"成功检索到 pptx_id:\", pptx_id)\n",
    "        break\n",
    "    except Exception as e:\n",
    "        print(\"您的Assistant正在努力制作幻灯片...\")\n",
    "        time.sleep(10)\n",
    "\n",
    "import io\n",
    "pptx_id = response.data[0].content[0].text.annotations[0].file_path.file_id\n",
    "ppt_file= client.files.content(pptx_id)\n",
    "file_obj = io.BytesIO(ppt_file.read())\n",
    "with open(\"咖哥花语秘境.pptx\", \"wb\") as f:\n",
    "    f.write(file_obj.getbuffer())\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
